package com.kgdev.cweb.beans;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.kgdev.cweb.entities.ManagedEntity;

public abstract class AbstractEJBBean<Entity extends ManagedEntity, EntityPK>
		implements EJBBean<Entity, EntityPK> {
	@PersistenceContext(unitName = "business-logic")
	protected EntityManager entityManager;

	protected Class<Entity> entityClass;

	protected AbstractEJBBean(Class<Entity> entityClass) {
		this.entityClass = entityClass;
	}

	@Override
	public void add(Entity entity) {
		entityManager.persist(entity);
	}

	@Override
	public void edit(Entity entity) {
		entityManager.merge(entity);
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Entity> findAll() {
		Query query = entityManager.createNamedQuery(entityClass
				.getSimpleName() + ".findAll");
		return query.getResultList();
	}

	@Override
	public Entity find(EntityPK id) {
		if (id == null)
			return null;
		return entityManager.find(entityClass, id);
	}

}
